Functions, loops and conditional statements

ANU BDSI
workshop
Introduction to R programming

Emi Tanaka

Biological Data Science Institute

3rd April 2024

Current learning objective

  • -Conduct elementary arithmetic operations using R
  • -Navigate the RStudio interactive development environment (IDE)
  • -Install external packages in R to extend functionality
  • -Comprehend various object types in R
  • -Manipulate lists, matrices, and vectors in R
  • -Compute basic summary statistics including mean, median, quartiles, and standard deviation using R
  • -Grasp the concept of missing values within the R environment
  • -Import and export data in R
  • Create basic functions, employ conditional statements, and utilize for loops in R
  • Decipher error messages and do basic troubleshooting

Functions

  • A function in R has three parts:
    • formals(): the list of input arguments,
    • body(): the code inside the function,
    • environment(): the environment (out of scope for this workshop).
  • Writing your own functions can make repetitive tasks easier.
  • You can make a new function using function().

Examining functions

  • Writing the name of the function without arguments shows the internal code:

Loops

Conditional statements

  • The condition in the if statement needs to evaluate to a single TRUE or FALSE
  • ifelse() is the vectorised

Example

Basic troubleshooting

If you encounter an error,

  1. Read the error message!
  2. Google the error message
  3. Ask for help with a reproducible example

🆘 Asking for help

  • What do you think about the question below?

🆘 Asking for help 1 Part 2

  • What do you think now?

I am looking to adjust the size of two separate ggplots within the same R chunk in Rmarkdown. These plots must be different when outputted as a pdf, so defining the dimensions at the beginning of the chunk doesn’t work. Does anyone have any ideas? My code is below.

```{r, fig.height = 3, fig.width = 3}
ggplot(df, aes(weight, height)) +
  geom_point()

ggplot(df, aes(height, volume)) +
  geom_point()
```

🆘 Asking for help 1 Part 3

  • Is this better?

I am looking to adjust the size of two separate ggplots within the same R chunk in Rmarkdown. These plots must be different when outputted as a pdf, so defining the dimensions at the beginning of the chunk doesn’t work. Does anyone have any ideas? My code is below.

```{r, fig.height = 3, fig.width = 3}
library(ggplot2)
ggplot(df, aes(weight, height)) +
  geom_point()

ggplot(df, aes(height, volume)) +
  geom_point()
```

🆘 Asking for help 1 Part 4

  • Okay better now?

I am looking to adjust the size of two separate ggplots within the same R chunk in Rmarkdown. These plots must be different when outputted as a pdf, so defining the dimensions at the beginning of the chunk doesn’t work. Does anyone have any ideas? My code is below.

```{r, fig.height = 3, fig.width = 3}
library(ggplot2)
df <- read.csv("mydata.csv")
ggplot(df, aes(weight, height)) +
  geom_point()

ggplot(df, aes(height, volume)) +
  geom_point()
```

🆘 Asking for help 1 Part 5

  • Are we done now?

I am looking to adjust the size of two separate ggplots within the same R chunk in Rmarkdown. These plots must be different when outputted as a pdf, so defining the dimensions at the beginning of the chunk doesn’t work. Does anyone have any ideas? My code is below.

```{r, fig.height = 3, fig.width = 3}
library(ggplot2)
ggplot(trees, aes(Girth, Height)) +
  geom_point()

ggplot(trees, aes(Height, Volume)) +
  geom_point()
```

❓ How to ask questions?

Checklist (note: not an exhaustive checklist)

If the question is asked in an public forum or similar:

If the problem is computer system related

If the problem is based on data

🆘 Asking for help 1 Check

🆘 Asking for help 2

  • How about the question on the right?
  • What makes it hard or easy for people to answer this question?

Session Information

You can easily get the session information in R using sessioninfo::session_info().
Scroll to see the packages used to make these slides.

sessioninfo::session_info()
─ Session info ───────────────────────────────────────────────────────────────
 setting  value
 version  R version 4.3.3 (2024-02-29)
 os       macOS Sonoma 14.4
 system   aarch64, darwin20
 ui       X11
 language (EN)
 collate  en_US.UTF-8
 ctype    en_US.UTF-8
 tz       Australia/Sydney
 date     2024-03-22
 pandoc   3.1.1 @ /Applications/RStudio.app/Contents/Resources/app/quarto/bin/tools/ (via rmarkdown)

─ Packages ───────────────────────────────────────────────────────────────────
 package     * version date (UTC) lib source
 cli           3.6.2   2023-12-11 [1] CRAN (R 4.3.1)
 colorspace    2.1-0   2023-01-23 [1] CRAN (R 4.3.0)
 digest        0.6.35  2024-03-11 [1] CRAN (R 4.3.1)
 dplyr       * 1.1.4   2023-11-17 [1] CRAN (R 4.3.1)
 evaluate      0.23    2023-11-01 [1] CRAN (R 4.3.1)
 fansi         1.0.6   2023-12-08 [1] CRAN (R 4.3.1)
 fastmap       1.1.1   2023-02-24 [1] CRAN (R 4.3.0)
 forcats     * 1.0.0   2023-01-29 [1] CRAN (R 4.3.0)
 generics      0.1.3   2022-07-05 [1] CRAN (R 4.3.0)
 ggplot2     * 3.5.0   2024-02-23 [1] CRAN (R 4.3.1)
 glue          1.7.0   2024-01-09 [1] CRAN (R 4.3.1)
 gtable        0.3.4   2023-08-21 [1] CRAN (R 4.3.0)
 hms           1.1.3   2023-03-21 [1] CRAN (R 4.3.0)
 htmltools     0.5.7   2023-11-03 [1] CRAN (R 4.3.1)
 jsonlite      1.8.8   2023-12-04 [1] CRAN (R 4.3.1)
 knitr         1.45    2023-10-30 [1] CRAN (R 4.3.1)
 lifecycle     1.0.4   2023-11-07 [1] CRAN (R 4.3.1)
 lubridate   * 1.9.3   2023-09-27 [1] CRAN (R 4.3.1)
 magrittr      2.0.3   2022-03-30 [1] CRAN (R 4.3.0)
 munsell       0.5.0   2018-06-12 [1] CRAN (R 4.3.0)
 pillar        1.9.0   2023-03-22 [1] CRAN (R 4.3.0)
 pkgconfig     2.0.3   2019-09-22 [1] CRAN (R 4.3.0)
 purrr       * 1.0.2   2023-08-10 [1] CRAN (R 4.3.0)
 R6            2.5.1   2021-08-19 [1] CRAN (R 4.3.0)
 readr       * 2.1.5   2024-01-10 [1] CRAN (R 4.3.1)
 rlang         1.1.3   2024-01-10 [1] CRAN (R 4.3.1)
 rmarkdown     2.26    2024-03-05 [1] CRAN (R 4.3.1)
 rstudioapi    0.15.0  2023-07-07 [1] CRAN (R 4.3.0)
 scales        1.3.0   2023-11-28 [1] CRAN (R 4.3.1)
 sessioninfo   1.2.2   2021-12-06 [1] CRAN (R 4.3.0)
 stringi       1.8.3   2023-12-11 [1] CRAN (R 4.3.1)
 stringr     * 1.5.1   2023-11-14 [1] CRAN (R 4.3.1)
 tibble      * 3.2.1   2023-03-20 [1] CRAN (R 4.3.0)
 tidyr       * 1.3.1   2024-01-24 [1] CRAN (R 4.3.1)
 tidyselect    1.2.0   2022-10-10 [1] CRAN (R 4.3.0)
 tidyverse   * 2.0.0   2023-02-22 [1] CRAN (R 4.3.0)
 timechange    0.3.0   2024-01-18 [1] CRAN (R 4.3.1)
 tzdb          0.4.0   2023-05-12 [1] CRAN (R 4.3.0)
 utf8          1.2.4   2023-10-22 [1] CRAN (R 4.3.1)
 vctrs         0.6.5   2023-12-01 [1] CRAN (R 4.3.1)
 withr         3.0.0   2024-01-16 [1] CRAN (R 4.3.1)
 xfun          0.42    2024-02-08 [1] CRAN (R 4.3.1)
 yaml          2.3.8   2023-12-11 [1] CRAN (R 4.3.1)

 [1] /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/library

──────────────────────────────────────────────────────────────────────────────

🎁 Reproducible Example with reprex LIVE DEMO

  • Copy your minimum reproducible example then run
reprex::reprex(session_info = TRUE)